<?php

class IndexAction extends PublicAction
{
    public function _initialize()
    {
        parent::_initialize();
    }

    //首页
    public function index()
    {
        $this->assign('isIndex', 1);
        $this->display();
    }

    //内容模型列表页
    public function lists()
    {
        //栏目id
        $catid = I('get.catid', 0, 'intval');

        if (empty($catid)) {
            $catdir = I('get.catdir');

            foreach ($this->Categorys as $key => $val) {
                if (!empty($val['catdir']) && $val['catdir'] == $catdir) {
                    $catid = $val['id'];
                }
            }
        }

        if (empty($catid) || !array_key_exists($catid, $this->Categorys)) {
            header("HTTP/1.0 404 Not Found");
            $this->display('./public/404.html');
            exit;
        }

        $cat = $this->Categorys[$catid];
        if ($cat['inherit'] == 1 && $cat['child'] == 1) {
            $cat = D('Admin/Category')->relation('Model')->where('parentid=' . $catid)->order('listorder desc,id asc')->find();
            $catid = $cat['id'];
        }

        $this->assign($cat);
        $modelname = $cat['model'];
        if ($cat['type'] == 1) {
            $modelname = 'Page';
        }
        $parencats = explode(',', $cat['arrparentid']);
        $max_parent_catid = empty($parencats[1]) ? $catid : $parencats[1];
        $assign['max_parent_catid'] = $max_parent_catid;
        $assign['max_parent_catname'] = $this->Categorys[$max_parent_catid]['catname'];
        $assign['model_name'] = $modelname;
        $assign['catid'] = $catid; //当前栏目id

        //seo信息
        $assign['seo_title'] = $cat['title'] ? $cat['title'] : $cat['catname'];
        $assign['seo_keywords'] = $cat['keywords'];
        $assign['seo_description'] = $cat['description'];

        if ($cat['type'] == 1) {

            $data = M('Page')->find($catid);

            $template_r = 'index';

            $this->assign($data);
        } else {
            $condition = array();
            $condition['status'] = 1;
            $condition['create_time'] = array('ELT', time());

            if (!empty($_REQUEST['type']) && is_array($_REQUEST['type'])) {
                foreach ($_REQUEST['type'] as $key => $value) {
                    if (!empty($value)) {
                        $condition[$key] = $value;
                    }
                }
                $this->assign($_REQUEST);
            }

            $model_db = M($modelname);

            if ($cat['child']) {
                $condition['catid'] = array('in', $cat['arrchildid']);
            } else {
                $condition['catid'] = $catid;
            }

            if (empty($cat['listtype'])) {

                $count = $model_db->where($condition)->count();

                if ($count) {
                    import("@.ORG.Page");
                    $listRows = !empty($cat['pagesize']) ? $cat['pagesize'] : C('PAGE_LISTROWS');
                    $page = new Page($count, $listRows);

                    $page->urlrule = geturl($cat, '');

                    $field = $this->Model[$this->Mod[$modelname]]['listfields'];
                    $field = $field ? $field : '*';

                    $assign['pages'] = $page->show();
                    $assign['list'] = $model_db->field($field)->where($condition)->order('listorder desc,id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
                }

                $template_r = 'list';

            } else {
                $template_r = 'index';
            }
        }

        $this->assign($assign);
        $template = $cat['template_list'] ? $cat['template_list'] : $template_r;

        $this->display($modelname . ':' . $template);
    }

    //内容模型详细页
    public function detail()
    {
        //栏目id
        $catid = I('get.catid', 0, 'intval');

        if (empty($catid)) {
            $catdir = I('get.catdir');

            foreach ($this->Categorys as $key => $val) {
                if (!empty($val['catdir']) && $val['catdir'] == $catdir) {
                    $catid = $val['id'];
                }
            }
        }

        if (empty($catid) || !array_key_exists($catid, $this->Categorys)) {
            header("HTTP/1.0 404 Not Found");
            $this->display('./public/404.html');
            exit;
        }

        $cat = $this->Categorys[$catid];
        $modelname = $cat['model'];

        $parencats = explode(',', $cat['arrparentid']);
        $max_parent_catid = empty($parencats[1]) ? $catid : $parencats[1]; //当前顶级栏目id
        $assign['max_parent_catid'] = $max_parent_catid; //当前顶级栏目id
        $assign['max_parent_catname'] = $this->Categorys[$max_parent_catid]['catname'];  //当前顶级栏目名称
        $assign['catid'] = $catid; //当前栏目id
        $assign['model_name'] = $modelname; //当前栏目模型名
        $this->assign($cat);

        $id = I('get.id', 0, 'intval');
        $p = I('p', 1, 'intval');

        $model_db = M($modelname);;
        $data = $model_db->find($id);
        if (empty($data)) {
            header("HTTP/1.0 404 Not Found");
            $this->display('./public/404.html');
            exit;
        }

        $listorder = $data['listorder'];

        //上一个，下一个
        $map['create_time'] = array('lt', time());
        $map['catid'] = $data['catid'];
        if ($listorder != 0) {
            $map['listorder'] = array('lt', $listorder);
            $prea = $model_db->field('title,url')->where($map)->order('listorder desc')->limit('1')->select();

            $map['listorder'] = array('gt', $listorder);
            $next = $model_db->field('title,url')->where($map)->order('listorder asc')->limit('1')->select();
        } else {
            $map['id'] = array('gt', $id);
            $prea = $model_db->field('title,url')->where($map)->order('id asc')->limit('1')->select();
            $map['id'] = array('lt', $id);
            $next = $model_db->field('title,url')->where($map)->order('id desc')->limit('1')->select();
        }

        $assign['prea'] = $prea[0];
        $assign['next'] = $next[0];

        $model_db->where("id=" . $id)->setInc('hits'); //添加点击次数

        //检查是否需要进行权限验证
        $noread = 0;
        if (!empty($data['readgroup'])) {
            if (!in_array($this->_groupid, explode(',', $data['readgroup']))) {
                $noread = 1;
            }
        } elseif ($cat['readgroup']) {
            if (!in_array($this->_groupid, explode(',', $cat['readgroup']))) {
                $noread = 1;
            }
        }

        if ($noread == 1) {
            $this->assign('jumpUrl', U('User/Login/index'));
            $this->error('您的浏览权限不够，请登陆或升级会员组！');
        }

        //seo设置
        $assign['seo_title'] = $data['title'] . '-' . $cat['catname'];
        $assign['seo_keywords'] = $data['keywords'];
        $assign['seo_description'] = $data['description'];

        $fields = getCache('Field_' . $cat['modelid']);

        foreach ($data as $key => $c_d) {
            if (!empty($fields[$key])) {
                $setup = !empty($fields[$key]['setup']) ? json_decode($fields[$key]['setup'], true) : '';

                if ($fields[$key]['type'] == 'relation') {
                    //关联信息
                    if (!empty($data[$key])) {
                        $temp_modelname = getModel($setup['modelid'], 'tablename');
                        $data[$key] = json_decode($data[$key], true);
                        $data[$key] = M($temp_modelname)->field('url,title,thumb')->where(array('id' => array('in', $data[$key])))->select();
                    }
                }

                if (!empty($setup['fieldtype']) && $setup['fieldtype'] == 'varchar' && $fields[$key]['type'] != 'text') {
                    $data[$key . '_old_val'] = $data[$key];
                    $data[$key] = fieldoption($fields[$key], $data[$key]);
                } elseif ($fields[$key]['type'] == 'images' || $fields[$key]['type'] == 'files') {
                    if (!empty($data[$key])) {
                        $data[$key] = json_decode($data[$key], true);
                    }
                }
            }
        }

        //手动分页
        $CONTENT_POS = strpos($data['content'], '[page]');
        if ($CONTENT_POS !== false) {

            $urlrule = geturl($cat, $data);
            $urlrule = str_replace('%7B%24page%7D', '{$page}', $urlrule);
            $contents = array_filter(explode('[page]', $data['content']));
            $pagenumber = count($contents);

            $pageurls = array();
            for ($i = 1; $i <= $pagenumber; $i++) {
                $pageurls[$i] = str_replace('{$page}', $i, $urlrule);
            }

            $assign['pages'] = content_pages($pagenumber, $p, $pageurls);
            //判断[page]出现的位置是否在文章开始
            if ($CONTENT_POS < 7) {
                $data['content'] = $contents[$p];
            } else {
                $data['content'] = $contents[$p - 1];
            }
        }
        $assign[strtolower($modelname)] = $data;

        //判断模板文件
        if (!empty($data['template'])) {
            $template = $data['template'];
        } elseif (!empty($cat['template_show'])) {
            $template = $cat['template_show'];
        } else {
            $template = 'detail';
        }

        $this->assign($assign);
        $this->display($modelname . ':' . $template);
    }

    //内容模型搜索
    public function search()
    {
        $keyword = $_GET['keyword'] = I('keyword');
        $modelid = $_GET['modelid'] = I('modelid', 2, 'intval');

        $this->assign($_REQUEST);

        //可搜索内容模型
        $model_search = array();
        foreach ($this->Model as $val) {
            if ($val['issearch'] == 1) {
                $model_search[] = $val;
            }
        }
        $this->assign('model_search', $model_search);

        $this->assign('seo_title', $this->Config['seo_title']);
        $this->assign('seo_keywords', $this->Config['seo_keywords']);
        $this->assign('seo_description', $this->Config['seo_description']);

        $modelname = $this->Model[$modelid]['tablename'];

        $where = array();
        $where['status'] = 1;
        $where['lang'] = LANG_ID;

        $where['title'] = array('like', "%$keyword%");

        $db = M($modelname);
        $count = $db->where($where)->count();

        $list = array();
        $pages = '';
        if ($count) {
            import("@.ORG.Page");
            $page = new Page($count, 10);
            $pages = $page->show();

            $field = 'id,url,title,keywords,description,thumb,create_time';

            $list = $db->field($field)->where($where)->order('listorder desc,id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
        }

        $this->assign('pages', $pages);
        $this->assign('list', $list);
        $this->assign($_GET);
        $this->display('Search:index');
    }
}